﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using NoteExpress;
using System.Threading;
using System.Linq;
using System.Xml.Linq;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;
using IronPython.Hosting;
using neut.Properties;
using System.Diagnostics;
//using Visio=Microsoft.Office.Interop.Visio;
//using Microsoft.Office.Interop.Visio.Extension;
namespace neut
{

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            Text = "NE User Tools " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Major.ToString() + "." +
                System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Minor.ToString();
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("是否关闭该工具？", "关闭通知", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly)
                == DialogResult.No)
                e.Cancel = true;
        }

        //[PreEmptive.Attributes.Feature("Load")]
        private void Form1_Load(object sender, EventArgs e)
        {
            HotKey.RegisterHotKey(Handle, 100, HotKey.KeyModifiers.Ctrl, Keys.E);
            HotKey.RegisterHotKey(Handle, 201, HotKey.KeyModifiers.Ctrl, Keys.S);
            HotKey.RegisterHotKey(Handle, 202, HotKey.KeyModifiers.Ctrl, Keys.G);
            HotKey.RegisterHotKey(Handle, 102, HotKey.KeyModifiers.Ctrl, Keys.D);
            HotKey.RegisterHotKey(Handle, 103, HotKey.KeyModifiers.Ctrl, Keys.F);
            HotKey.RegisterHotKey(Handle, 104, HotKey.KeyModifiers.Ctrl, Keys.B);
            HotKey.RegisterHotKey(Handle, 105, HotKey.KeyModifiers.Ctrl, Keys.I);


            DirectoryInfo TheFolder = new DirectoryInfo(".\\search");
            foreach (var file in TheFolder.GetFiles())
            {
                if (file.Extension == ".py")
                {
                    this.cbEngine.Items.Add(new ComboBoxItem() { Text = file.Name, Value = file.FullName });
                }
            }
            cbEngine.SelectedIndex = 0;

            //var tmpf = Settings.Default.LastWorkFolder.ToNEFolder();
            //if (tmpf != null)
            //{
            //    textBox31.Text = tmpf.Title;
            //    textBox31.Tag = tmpf;
            //}

            textBox8.Text = Settings.Default.PdfOutputFolder;

        }
        ///
        /// 监视Windows消息
        /// 重载WndProc方法，用于实现热键响应
        ///
        ///
        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;
            //按快捷键
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    switch (m.WParam.ToInt32())
                    {
                        case 201:     //按下的是Ctrl+S
                            button46_Click(this, null);
                            button32_Click(null, null);
                            break;
                        case 202:     //按下的是Ctrl+G
                            button16_Click(this, null);
                            break;
                        case 100:     //按下的是Ctrl+e
                            //此处填写快捷键响应代码
                            var ne2 = new NEHost2();
                            ne2.MainForm.Active = ne2.MainForm.Active ? false : true;
                            break;
                        case 102:     //按下的是Ctrl+D
                            this.WindowState = this.WindowState == FormWindowState.Minimized ? FormWindowState.Normal : FormWindowState.Minimized;
                            break;
                        case 103://按下的是Ctrl+F
                            button37_Click(this, null);
                            break;
                        case 104://按下的是Ctrl+B
                            button9_Click(this, null);
                            break;
                        case 105://按下的是Ctrl+I
                            button35_Click(this, null);
                            break;
                    }
                    break;
            }
            base.WndProc(ref m);
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            //HotKey.UnregisterHotKey(Handle, 100);
            HotKey.UnregisterHotKey(Handle, 100);
            HotKey.UnregisterHotKey(Handle, 102);
            HotKey.UnregisterHotKey(Handle, 201);
            HotKey.UnregisterHotKey(Handle, 202);
            HotKey.UnregisterHotKey(Handle, 103);
            HotKey.UnregisterHotKey(Handle, 104);
            HotKey.UnregisterHotKey(Handle, 105);
        }

        //============查重
        private void button4_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        INEHost2 _ne = null;
        INEHost2 ne
        {
            get
            {
                try
                {
                    if (_ne == null)
                        _ne = new NEHost2();
                }
                catch
                {
                    throw new Exception("Can't Load NoteExpress");
                }

                return _ne;
            }
        }
        //INEHost2 ne = new NEHost2();
        INEFolder folder1, folder2, folder3;
        private void button1_Click(object sender, EventArgs e)
        {
            folder1 = ne.Libraries.ActiveFolder;
            textBox1.Text = folder1.Title;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            folder2 = ne.Libraries.ActiveFolder;
            textBox2.Text = folder2.Title;
        }

        INEItem[] FoldersShare(INEFolder folder1, bool iteration1, INEFolder folder2, bool iteration2)
        {
            var rt = new List<INEItem>();
            var dic1 = new Dictionary<string, INEItem>();
            if (!iteration1)
                for (int i = 0; i < folder1.Items.Count; i++)
                {
                    var tmp = folder1.Items.get_Items(i);
                    dic1.Add(tmp.UID, tmp);
                }
            else
                FindItems(folder1, checkBox4.Checked, ref dic1);
            var dic2 = new Dictionary<string, INEItem>();
            if (!iteration2)
                for (int i = 0; i < folder2.Items.Count; i++)
                {
                    var tmp = folder2.Items.get_Items(i);
                    dic2.Add(tmp.UID, tmp);
                }
            else
                FindItems(folder2, checkBox7.Checked, ref dic2);
            foreach (var t in dic1)
            {
                if (dic2.ContainsKey(t.Key))
                    rt.Add(t.Value);
            }

            return rt.ToArray();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = @"工作中……";

            var thread = new Thread(new ThreadStart(
                () =>
                {
                    //var sw = new System.Diagnostics.Stopwatch();
                    //sw.Start();

                    var dic1 = new Dictionary<string, INEItem>();
                    if (!checkBox1.Checked)
                        for (int i = 0; i < folder1.Items.Count; i++)
                        {
                            var tmp = folder1.Items.get_Items(i);
                            dic1.Add(tmp.UID, tmp);
                        }
                    else
                        FindItems(folder1, checkBox4.Checked, ref dic1);
                    var dic2 = new Dictionary<string, INEItem>();
                    if (!checkBox2.Checked)
                        for (int i = 0; i < folder2.Items.Count; i++)
                        {
                            var tmp = folder2.Items.get_Items(i);
                            dic2.Add(tmp.UID, tmp);
                        }
                    else
                        FindItems(folder2, checkBox7.Checked, ref dic2);
                    foreach (var t in dic1)
                    {
                        if (dic2.ContainsKey(t.Key))
                            if (!folder3.LinkItem(t.Value))
                                throw new Exception("Error");
                    }

                    var tt = ne.Libraries.ActiveFolder;
                    var item = folder3.GetRelatedItem();
                    item.set_Values("Abstract", DateTime.Now.ToString() + "\r\n"
                        + folder1.GetFullName() + " (" + (checkBox1.Checked ? "Iteration" : "No Iteration") + ")\r\n"
                        + folder2.GetFullName() + " (" + (checkBox2.Checked ? "Iteration" : "No Iteration") + ")\r\n"
                        + item.Values["Abstract"]);
                    tt.Activate();

                    toolStripStatusLabel1.Text = @"工作完成！";

                    //sw.Stop();
                    //MessageBox.Show(sw.ElapsedMilliseconds.ToString());
                }));
            thread.Start();
        }

        void FindItems(INEFolder folder, bool bStartFolder, ref Dictionary<string, INEItem> items)
        {
            for (int i = 0; i < folder.Items.Count; i++)
            {
                var tmp = folder.Items.get_Items(i);
                items[tmp.UID] = tmp;
            }
            for (int i = 0; i < folder.Count; i++)
            {
                var tmp = folder.Children[i];
                if (bStartFolder && tmp.Title.IndexOf("*") == 0) continue;
                FindItems(folder.get_Children(i), bStartFolder, ref items);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            folder3 = ne.Libraries.ActiveFolder;
            textBox3.Text = folder3.Title;
        }

        private void button38_Click_1(object sender, EventArgs e)
        {
            if (textBox3.Text != string.Empty)
            {
                var t = ne.Libraries.ActiveFolder;
                folder3 = folder2.Add(textBox3.Text);
                textBox3.Text = textBox3.Text;
                t.Activate();
            }
            else
            {
                var tmp = "&" + folder1.Title;

                INEFolder folder = null;
                for (var i = 0; i < folder2.Count; i++)
                {
                    if (folder2.Children[i].Title == tmp)
                    {
                        folder = folder2.Children[i];
                        textBox3.Text = tmp;
                        break;
                    }
                }
                if (folder == null)
                {
                    var t = ne.Libraries.ActiveFolder;
                    folder = folder2.Add(tmp);
                    textBox3.Text = tmp;
                    t.Activate();
                }

                folder3 = folder;
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            //(new AboutBox()).ShowDialog();
            Process.Start(@"http://neut.codeplex.com/documentation");
        }

        //============删重
        INEFolder folder4, folder5;
        private void button10_Click(object sender, EventArgs e)
        {
            folder4 = ne.Libraries.ActiveFolder;
            textBox4.Text = folder4.Title;
        }

        private void button11_Click(object sender, EventArgs e)
        {
            folder5 = ne.Libraries.ActiveFolder;
            textBox5.Text = folder5.Title;
        }
        void DeleteItem2(INEFolder folder1, INEFolder folder2, bool bSelf)
        {
            if (folder1.UID == folder2.UID)
                return;
            folder1.DeleteItems(folder2.Items, false);
            if (checkBox3.Checked)
                for (int i = 0; i < folder2.Count; i++)
                {
                    DeleteItem(folder1, folder2.get_Children(i), bSelf);
                }
            if (checkBox9.Checked)
                for (int i = 0; i < folder1.Count; i++)
                {
                    DeleteItem2(folder1.get_Children(i), folder2, bSelf);
                }
        }
        private void button7_Click(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = @"工作中……";

            var thread = new Thread(new ThreadStart(
                () =>
                {
                    //if (!checkBox9.Checked)
                    //    if (!checkBox3.Checked)
                    //        folder4.DeleteItems(folder5.Items, false);
                    //    else
                    //        DeleteItem(folder4, folder5);
                    //else
                    DeleteItem2(folder4, folder5, checkBox11.Checked);

                    toolStripStatusLabel1.Text = @"工作完成！";
                }));
            thread.Start();
        }

        private void button12_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        //============合并
        //XElement ref2;
        //INEFolder folderref2;
        //INEItem ref2item;
        private void button14_Click(object sender, EventArgs e)
        {
            if (ne.Internals.RefSelectionCount() != 1)
                throw new Exception("You can't select more than one reference.");
            //ref2 = XElement.Parse(ne.Internals.GetSelectedReferences());
            //textBox7.Text = ref2.Descendants("ID").Single().Value;
            //for (int i = 0; i < ne.Libraries.ActiveFolder.Items.Count; i++)
            //{
            //    var tmp = ne.Libraries.ActiveFolder.Items.get_Items(i);
            //    if (ref2.Descendants("ID").Single().Value == tmp.get_Values("ID"))
            //    {
            //        folderref2 = ne.Libraries.ActiveFolder;
            //        ref2item = tmp;
            //        break;
            //    }
            //}
            textBox7.Text = ne.Libraries.SelectedItems.FirstItem().Values["ID"];
            textBox7.Tag = ne.Libraries.SelectedItems.FirstItem();
            button14.Tag = ne.Libraries.ActiveFolder;
        }
        //INEItem ref1;
        //INEFolder folderref1;
        private void button13_Click(object sender, EventArgs e)
        {
            if (ne.Internals.RefSelectionCount() != 1)
                throw new Exception("You can't select more than one reference.");
            //var ref1xml = XElement.Parse(ne.Internals.GetSelectedReferences());
            //folderref1 = ne.Libraries.ActiveFolder;
            //for (int i = 0; i < folderref1.Items.Count; i++)
            //{
            //    var tmp = folderref1.Items.get_Items(i);
            //    if (ref1xml.Descendants("ID").Single().Value == tmp.get_Values("ID"))
            //    {
            //        ref1 = tmp;
            //        textBox6.Text = ref1xml.Descendants("ID").Single().Value;
            //        break;
            //    }
            //}
            textBox6.Text = ne.Libraries.SelectedItems.FirstItem().Values["ID"];
            textBox6.Tag = ne.Libraries.SelectedItems.FirstItem();
        }

        string XMLtoInner(string name)
        {
            switch (name)
            {
                case "_db_updated": return "Database Updated";
                case "_modified": return "Date Accessed";
                case "_created": return "Date Created";
                case "_accessed": return "Date Modified";
                case "_custom1": return "Custom 1";
                case "_custom2": return "Custom 2";
                case "_custom3": return "Custom 3";
                case "_custom4": return "Custom 4";
                case "_custom5": return "Custom 5";
                case "_custom_int1": return "Custom Integer 1";
                case "_custom_int2": return "Custom Integer 2";
                case "_custom_int3": return "Custom Integer 3";
                case "_custom_int4": return "Custom Integer 4";
                case "_custom_int5": return "Custom Integer 5";
                default: return name.Substring(1, name.Length - 1);
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = @"工作中……";


            var ref1 = textBox6.Tag.ToNEItem();
            var ref2 = textBox7.Tag.ToNEItem();
            foreach (var t in NE2Extension.NEItemField)
            {
                var t1 = ref1.get_Values(t);
                var t2 = ref2.get_Values(t);
                if ((t2 != null && t2 != string.Empty) &&
                    ((t1 == null || t1 == string.Empty) || radioButton2.Checked))
                    ref1.set_Values(t, t2);
            }

            foreach (var t in ref2.GetFolders())
            {
                t.LinkItem(ref1);
            }

            if (radioButton8.Checked)
                button14.Tag.ToNEFolder().DeleteItem(ref2, false);
            else if (radioButton9.Checked)
            {
                foreach (var t in ref2.GetFolders())
                {
                    t.DeleteItem(ref2, false);
                }
            }

            toolStripStatusLabel1.Text = @"工作完成！";

            textBox6.Text = ""; textBox6.Tag = null;
            textBox7.Text = ""; textBox7.Tag = null;
        }

        void incoporate(INEItem to, INEItem from)
        {
            var ref1 = to.ToNEItem();
            var ref2 = from.ToNEItem();
            foreach (var t in NE2Extension.NEItemField)
            {
                var t1 = ref1.get_Values(t);
                var t2 = ref2.get_Values(t);
                if ((t2 != null && t2 != string.Empty) &&
                    ((t1 == null || t1 == string.Empty) || radioButton2.Checked))
                    ref1.set_Values(t, t2);
            }

            foreach (var t in ref2.GetFolders())
            {
                t.LinkItem(ref1);
            }

            if (radioButton8.Checked)
                button14.Tag.ToNEFolder().DeleteItem(ref2, false);
            else if (radioButton9.Checked)
            {
                foreach (var t in ref2.GetFolders())
                {
                    t.DeleteItem(ref2, false);
                }
            }
        }
        /*
        void incoporate(INEItem to, INEItem from)
        {
            string[] t = new string[]{
                "ID",
"UID",
"Title",
"Template",
"Star",
"Tag",
"Author",
"Year",
"_short_Title",
"_abstract",
"_notes",
"_url",
"_secondary_author",
"_secondary_title",
"_place_published",
"_publisher",
"_journal",
"_volume",
"_issue",
"_num_volumes",
"_number",
"_pages",
"_num_words",
"_price",
"_section",
"_tertiary_author",
"_tertiary_title",
"_cited_count",
"_ref_count",
"_ref_cite",
"_edition",
"_doi",
"_date_display",
"_date",
"_type_work",
"_subsidiary_author",
"_alternate_title",
"_isbn",
"_ori_publication",
"_reprint_edition",
"_reviewed_item",
"_accession_num",
"_call_num",
"_cate",
"_label",
"_bibtex_key",
"_keywords",
"_subject_headings",
"_subject",
"_image",
"_author_aff",
"_author_adr",
"_caption",
"_translated_author",
"_translated_title",
"_db_provider",
"_db_updated",
"_language",
"_country",
"_modified",
"_created",
"_accessed",
"_custom1",
"_custom2",
"_custom3",
"_custom4",
"_custom5",
"_custom_int1",
"_custom_int2",
"_custom_int3",
"_custom_int4",
"_custom_int5"            };

            foreach (var i in t)
            {
                if (i == "ID" || i == "UID")
                    continue;
                var t1 = to.get_Values(i);
                var t2 = from.get_Values(i);

                if ((t2 != null && t2 != string.Empty) &&
                       ((t1 == null || t1 == string.Empty) || radioButton2.Checked))
                    to.set_Values(i, t2);
            }

            //var refxml = XElement.Parse(ne.Internals.GetSelectedReferences());
            //var refitem = (from t in refxml.Elements()
            //              where t.Element("UID").Value==to.get_Values("UID")
            //              select t).Single();

            //foreach (var t in refitem.Elements())
            //{
            //    if (t.Name.LocalName == "ID" || t.Name.LocalName == "UID")
            //        continue;

            //    if (t.Name.LocalName == "Details")
            //    {
            //        foreach (var tt in t.Elements())
            //        {
            //            var name = XMLtoInner(tt.Name.LocalName);
            //            var t1 = ref1.get_Values(name);
            //            var t2 = tt.Value.ToString();
            //            if ((t2 != null && t2 != string.Empty) &&
            //                ((t1 == null || t1 == string.Empty) || radioButton2.Checked))
            //                ref1.set_Values(name, t2);
            //        }
            //    }
            //    else if (t.Name.LocalName == "Extra")
            //    {
            //        foreach (var tt in t.Elements())
            //        {
            //            var name = XMLtoInner(tt.Name.LocalName);
            //            var t1 = ref1.get_Values(name);
            //            var t2 = tt.Value.ToString();
            //            if ((t2 != null && t2 != string.Empty) &&
            //                ((t1 == null || t1 == string.Empty) || radioButton2.Checked))
            //                ref1.set_Values(name, t2);
            //        }
            //    }
            //    else
            //    {
            //        var t1 = ref1.get_Values(t.Name.LocalName);
            //        var t2 = t.Value.ToString();
            //        if ((t2 != null && t2 != string.Empty) &&
            //            ((t1 == null || t1 == string.Empty) || radioButton2.Checked))
            //            ref1.set_Values(t.Name.LocalName, t2);
            //    }
            //}    
        }
    
        private void button23_Click(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = @"工作中……";

            var thread = new Thread(new ThreadStart(
                () =>
                {
                    var itemlist = new Dictionary<string, INEItem>();
                    var items = ne.Libraries.SelectedItems;
                    for (int i = 0; i < items.Count; i++)
                    {
                        var t = items.get_Items(i);
                        itemlist.Add(t.get_Values("Title").Replace(" ", "").ToLower(), t);
                    }
                    var del = ne.Libraries.ActiveFolder.NewItems();
                    for (int i = 0; i < ne.Libraries.ActiveFolder.Items.Count; i++)
                    {
                        var t = ne.Libraries.ActiveFolder.Items.get_Items(i);

                        if (itemlist.Keys.Contains(t.get_Values("Title").Replace(" ", "").ToLower()))
                        {
                            var tmp = itemlist[t.get_Values("Title").Replace(" ", "").ToLower()];
                            if (t.UID == tmp.UID)
                                continue;
                            incoporate(tmp, t);
                            del.Add(t);
                        }
                    }

                    if (!radioButton7.Checked)
                        ne.Libraries.ActiveFolder.DeleteItems(del, false);

                    toolStripStatusLabel1.Text = @"工作完成！";
                }));
            thread.Start();
        }
    */
        private void button15_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        //==============================================归类
        INEItem GetSelectedItem(out INEFolder folder)
        {
            folder = null;
            if (ne.Internals.RefSelectionCount() != 1)
                throw new Exception("You can't select more than one reference.");
            var refxml = XElement.Parse(ne.Internals.GetSelectedReferences());
            for (int i = 0; i < ne.Libraries.ActiveFolder.Items.Count; i++)
            {
                var tmp = ne.Libraries.ActiveFolder.Items.get_Items(i);
                if (refxml.Descendants("ID").Single().Value == tmp.get_Values("ID"))
                {
                    folder = ne.Libraries.ActiveFolder;
                    return tmp;
                }
            }
            return null;
        }

        private void button18_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        INEFolder FindSubParent(INEFolder folder)
        {
            var tmp = folder;
            while (tmp.Parent.UID != ne.Libraries.ActiveFolder.ParentLibrary.References.UID)
            {
                tmp = tmp.Parent;
            }
            return tmp;
        }


        //===================================
        List<string> refinput = new List<string>();
        private void button17_Click(object sender, EventArgs e)
        {
            refinput.Clear();
            var form = new RefInput();
            form.ShowDialog();
            MemoryStream MStream = new MemoryStream(System.Text.ASCIIEncoding.UTF8.GetBytes(form.RefString));
            using (var sr = new StreamReader(MStream))
            {
                string tmp;
                while ((tmp = sr.ReadLine()) != null)
                {
                    refinput.Add(tmp);
                }
            }

            //textBox10.Text = refinput.Count + (radioButton12.Checked ? " Citing" : " Cited");
        }
        INEFolder refFolder;
        private void button19_Click(object sender, EventArgs e)
        {
            refFolder = ne.Libraries.ActiveFolder;
            textBox11.Text = refFolder.Title;
        }

        private void button20_Click(object sender, EventArgs e)
        {
            if (refinput.Count < 1)
            {
                MessageBox.Show("没有录入参考文献", "", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            toolStripStatusLabel1.Text = @"工作中……";

            var thread = new Thread(new ThreadStart(
                () =>
                {
                    var dic = new Dictionary<string, INEItem>();
                    if (!checkBox6.Checked)
                        for (int i = 0; i < refFolder.Items.Count; i++)
                        {
                            var tmp = refFolder.Items.get_Items(i);
                            dic.Add(tmp.UID, tmp);
                        }
                    else
                        FindItems(refFolder, true, ref dic);

                    INEFolder subfolder = null;
                    foreach (var t in dic)
                    {
                        bool bFind = false;
                        var tmp = t.Value.get_Values("Title");
                        foreach (var i in refinput)
                        {
                            if (i.IndexOf(tmp) > -1)
                            {
                                bFind = true;
                                break;
                            }
                        }
                        if (!bFind)
                        {
                            if (subfolder == null) subfolder = refFolder.Add(".tmp");

                            subfolder.LinkItem(t.Value);
                        }
                    }

                    toolStripStatusLabel1.Text = @"工作完成！";
                }));

            thread.Start();
        }

        private void button21_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        //======================分布
        /*
        List<Thread> listthread = new List<Thread>();
        void FindItems(INEFolder folder, XDocument xml)
        {
            var thread = new Thread(new ThreadStart(
    () =>
    {
        for (int i = 0; i < folder.Items.Count; i++)
        {
            var tmp = folder.Items.get_Items(i);
            XElement t = null;

            t = new XElement("Item", new XAttribute("UID", tmp.UID), folder.GetFullName());
            //Monitor.Enter(xml);
            xml.Root.Add(t);
            // Monitor.Exit(xml);
        }
    }));
            listthread.Add(thread);
            thread.Start();

            for (int i = 0; i < folder.Count; i++)
            {
                FindItems(folder.get_Children(i), xml);
            }
        }

        XElement GetTree(string name, Dictionary<string, INEItem> dic, XDocument doc)
        {
            var items = from i in doc.Root.Elements()
                        where dic.Keys.Contains(i.Attribute("UID").Value)
                        select i;
            XElement rt = new XElement(name);

            foreach (var n in items)
            {
                var t = n.Value;

                var i = rt;
                var tmp = t.Split('\\');
                foreach (var tt in tmp)
                {
                    XElement j = null;
                    var sel = from m in i.Elements("Folder") where m.Attribute("Name").Value == tt select m;
                    if (sel.Count() < 1)
                    {
                        j = new XElement("Folder", new XAttribute("Name", tt));
                        i.Add(j);
                    }
                    else
                    {
                        j = sel.Single();
                    }

                    i = j;
                }
                var sel2 = from m in i.Elements("Item") where m.Value == n.Attribute("UID").Value select m;
                if (sel2.Count() < 1)
                    i.Add(new XElement("Item", n.Attribute("UID")));

            }

            return rt;
        }
        INEFolder objfolder;
        private void button25_Click(object sender, EventArgs e)
        {
            objfolder = ne.Libraries.ActiveFolder;
            textBox13.Text = objfolder.Title;
        }
        XDocument doc;
        private void button27_Click(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = @"工作中……";

            var thread = new Thread(new ThreadStart(
                () =>
                {
                    //var sw = new System.Diagnostics.Stopwatch();

                    var dic = new Dictionary<string, INEItem>();
                    if (!checkBox8.Checked)
                        for (int i = 0; i < objfolder.Items.Count; i++)
                        {
                            var tmp = objfolder.Items.get_Items(i);
                            dic.Add(tmp.UID, tmp);
                        }
                    else
                        FindItems(objfolder, ref dic);

                    //sw.Start();

                    if (doc == null || checkBox7.Checked)
                    {
                        if (doc == null)
                            doc = new XDocument(new XElement("Items-Folder"));

                        FindItems(ne.Libraries.ActiveFolder.ParentLibrary.References, doc);
                    }
                    listthread.ForEach((a) => { a.Join(); });

                    //sw.Stop();
                    //MessageBox.Show(sw.ElapsedMilliseconds.ToString());

                    var rt = GetTree(ne.Libraries.ActiveFolder.Title, dic, doc);

                    DistributionForm disForm = new DistributionForm();
                    disForm.FolderTree = rt;
                    disForm.ShowDialog();

                    toolStripStatusLabel1.Text = @"工作完成！";
                }));

            thread.Start();
        }
        */

        //=================================================删空格
        string ReplaceBlank(string input)
        {
            var tmp = input;
            string regex1 = @"[^a-z\s](\s+)[^a-z\s]";
            string regex2 = @"[^a-z\s]+(\s+)[a-z]";
            string regex3 = @"[a-z](\s+)[^a-z\s]+";
            tmp = Regex.Replace(tmp, regex1, (match) =>
            {
                string matchValue = match.Value;
                return matchValue.Replace(" ", "");
            }, RegexOptions.IgnoreCase);
            tmp = Regex.Replace(tmp, regex2, (match) =>
            {
                string matchValue = match.Value;
                return matchValue.Replace(" ", "");
            }, RegexOptions.IgnoreCase);
            tmp = Regex.Replace(tmp, regex3, (match) =>
            {
                string matchValue = match.Value;
                return matchValue.Replace(" ", "");
            }, RegexOptions.IgnoreCase);
            tmp = Regex.Replace(tmp, @"\S(\s{2,})\S", (match) =>
            {
                string matchValue = match.Value;
                return matchValue[0] + " " + matchValue[matchValue.Length - 1];
            }, RegexOptions.IgnoreCase);
            tmp = Regex.Replace(tmp, @"[a-z][,.:;?][a-z]+", (match) =>
            {
                string matchValue = match.Value;
                return matchValue.Substring(0, 2) + " " + matchValue.Substring(2);
            }, RegexOptions.IgnoreCase);
            tmp = tmp.TrimStart().TrimEnd();
            return tmp;
        }

        private void button30_Click(object sender, EventArgs e)
        {
            textBox14.Text = textBox14.Text.Replace("-\r\n", "").Replace("\r\n", " ");
        }

        private void button18_Click_1(object sender, EventArgs e)
        {
            var ne2 = new NEHost2();
            var item = ne2.Libraries.SelectedItems.FirstItem();
            button18.Tag = item;
            textBox21.Text = item.Values["ID"] + "," + item.Values["Title"];
            toolStripStatusLabel1.Text = @"Set current item！";
        }

        private void button24_Click_1(object sender, EventArgs e)
        {
            var tmp = textBox14.Text;

            //textBox14.Text = ReplaceBlank(textBox14.Text);
            var ipy = Python.CreateRuntime();
            dynamic t = ipy.UseFile("ReplaceBlankScrip.py");
            textBox14.Text = t.ReplaceBlank(textBox14.Text);
        }

        private void button26_Click_1(object sender, EventArgs e)
        {
            if (button18.Tag != null)
            {
                var tmp = "";
                tmp = "[NEID:" + button18.Tag.ToNEItem().get_Values("ID") + "]";
                if (!radioButton14.Checked)
                    textBox14.Text = this.radioButton10.Checked ? tmp + textBox14.Text + "\r\n" : textBox14.Text + tmp;
            }
            else
                textBox14.Text += "\r\n";

            textBox14.SelectAll();
            textBox14.Copy();
            textBox14.Text = "";
            //if (DialogResult.Yes == MessageBox.Show("是否最小化窗体？", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                this.WindowState = FormWindowState.Minimized;
        }


        //========================自定义
        //INEItem GetSelectedItem()
        //{

        //    if (ne.Internals.RefSelectionCount() != 1)
        //        throw new Exception("You can't select more than one reference.");
        //    var refxml = XElement.Parse(ne.Internals.GetSelectedReferences());
        //    for (int i = 0; i < ne.Libraries.ActiveFolder.Items.Count; i++)
        //    {
        //        var tmp = ne.Libraries.ActiveFolder.Items.get_Items(i);
        //        if (refxml.Descendants("ID").Single().Value == tmp.get_Values("ID"))
        //        {
        //            return tmp;
        //        }
        //    }
        //    return null;
        //}
        /*
        INEItem objitemzdy;
        private void button28_Click(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = @"";
            objitemzdy = ne.Libraries.SelectedItems.get_Items(0);
            textBox15.Text = objitemzdy.get_Values("Title");

            textBox16.Text = objitemzdy.get_Values("Custom 1");
            textBox17.Text = objitemzdy.get_Values("Custom 2");
            textBox18.Text = objitemzdy.get_Values("Custom 3");
            RefNo.Text = objitemzdy.get_Values("Custom 4");
            textBox20.Text = objitemzdy.get_Values("Custom 5");
            textBox21.Text = objitemzdy.get_Values("Author Address");
        }

        private void button29_Click(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = @"工作中……";

            var thread = new Thread(new ThreadStart(
                () =>
                {
                    objitemzdy.set_Values("Custom 1", textBox16.Text);
                    objitemzdy.set_Values("Custom 2", textBox17.Text);
                    objitemzdy.set_Values("Custom 3", textBox18.Text);
                    objitemzdy.set_Values("Custom 4", RefNo.Text);
                    objitemzdy.set_Values("Custom 5", textBox20.Text);
                    objitemzdy.set_Values("Author Address", textBox21.Text);

                    textBox16.Text = "";
                    textBox17.Text = "";
                    textBox18.Text = "";
                    RefNo.Text = "";
                    textBox20.Text = "";
                    textBox21.Text = "";


                    toolStripStatusLabel1.Text = @"工作完成！";
                    textBox15.Text = "";
                }));
            thread.Start();
        }
        */

        //===============================工作
        //INEFolder workFolder;
        private void button32_Click(object sender, EventArgs e)
        {
            textBox23.Tag = ne.Libraries.ActiveFolder.AddInHistory();
            textBox23.Text = textBox23.Tag.ToNEFolder().Title;

            comboBox4.Text = "";
            comboBox4.Items.Clear();
            var ne2 = new NoteExpress.NEHost2();
            var items = ne2.Libraries.SelectedItems;
            var folder = ne2.Libraries.ActiveFolder;
            var tmp = folder.GetRelatedItem();
            if (tmp == null) return;
            var str = tmp.Values["Custom 1"];

            XDocument xmldoc = null;
            if (str != null && str != string.Empty)
            {

                var tr = new StringReader(str);
                xmldoc = XDocument.Load(tr);

                XElement xmle = xmldoc.Root.Element("ReadHistory");
                if (xmle != null && xmle.Elements().Count() > 0)
                {
                    comboBox4.Items.AddRange(xmle.Elements().Select(x => x.Name.LocalName).ToArray());
                    comboBox4.SelectedIndex = 0;
                }

            }
        }

        private void button34_Click(object sender, EventArgs e)
        {
            if (textBox23.Tag == null) return;
            backFolder = ne.Libraries.ActiveFolder;
            textBox23.Tag.ToNEFolder().Activate();

            ne.MainForm.Show();
            //ne.MainForm.Active=false;
        }
        //INEItem workItem;
        private void button33_Click(object sender, EventArgs e)
        {
            //workItem = GetSelectedItem();
            button18.Tag = ne.Libraries.SelectedItems.FirstItem();

            var ser = new System.Xml.Serialization.XmlSerializer(typeof(SerializableDictionary<string, string>));
            StringBuilder sb = new StringBuilder();
            SerializableDictionary<string, string> list;
            var ne2 = new NoteExpress.NEHost2();
            var folder = ne2.Libraries.ActiveFolder;
            var tmp = folder.GetRelatedItem();
            if (tmp == null) return;
            var str = tmp.Values["Custom 1"];
            if (str != null && str != string.Empty)
            {
                var sr = new StringReader(str);
                list = (SerializableDictionary<string, string>)ser.Deserialize(sr);

                if (list.Keys.Contains(button18.Tag.ToNEItem().Values["ID"]))
                    toolStripStatusLabel1.Text = @"状态：已处理 " + list[button18.Tag.ToNEItem().Values["ID"]];
                else
                    toolStripStatusLabel1.Text = @"状态：未处理";
            }
        }


        private void button68_Click(object sender, EventArgs e)
        {
            var text = (comboBox4.Text);

            if (textBox23.Tag == null) return;
            var folder = textBox23.Tag.ToNEFolder();
            var doc = folder.GetRelatedItem().GetCustom();

            var tmp = doc.Root.Element("ReadHistory").Element(comboBox4.Text);
            if (tmp != null)
            {
                tmp.Remove();
                folder.GetRelatedItem().SaveCustom(doc);
            }

            //var tmp = folder.GetRelatedItem();
            //var str = tmp.Values["Custom 1"];

            //XDocument xmldoc;
            //var tr3 = new StringReader(str);
            //xmldoc = XDocument.Load(tr3);
            //xmldoc.Root.Element("ReadHistory").Element(comboBox4.Text).Remove();
            ////tmp.Values["Custom 1"] = xmldoc.ToString();

            //StringBuilder sb = new StringBuilder();
            //TextWriter tr = new StringWriter(sb);
            //xmldoc.Save(tr);
            //tmp.Values["Custom 1"] = sb.ToString();

            //var items = folder.Items;
            //for (var i = 0; i < items.Count; i++)
            //{
            //    var item = items.get_Items(i);
            //    if (tmp.UID == item.UID) continue;
            //    var str2 = item.Values["Custom 1"];

            //    xmldoc = null;
            //    if (str2 != null && str2 != string.Empty)
            //    {
            //        var tr2 = new StringReader(str2);
            //        xmldoc = XDocument.Load(tr2);

            //        XElement xmle = xmldoc.Root.Element("ReadHistory");
            //        var tmp=(from t in xmle.Elements())

            //        if (xmle != null && xmle.Element(comboBox4.Text) != null)
            //        {
            //            xmle.Element(folder.UID).Remove();
            //        }
            //        item.Values["Custom 1"] = xmldoc.ToString();
            //    }

            //}

            comboBox4.Items.RemoveAt(comboBox4.SelectedIndex);
        }

        private void button67_Click(object sender, EventArgs e)
        {
            comboBox4.Items.Add(comboBox4.Text);

            if (textBox23.Tag == null) return;
            var folder = textBox23.Tag.ToNEFolder();
            var tmp = folder.GetRelatedItem();
            var str = tmp.Values["Custom 1"];

            XDocument xmldoc = tmp.GetCustom();

            XElement xmle = xmldoc.Root.Element("ReadHistory");
            if (xmle == null) xmldoc.Root.Add(new XElement("ReadHistory"));

            xmle = xmldoc.Root.Element("ReadHistory").Element(comboBox4.Text);
            if (xmle == null)
            {
                xmle = new XElement(comboBox4.Text);
                xmldoc.Root.Element("ReadHistory").Add(xmle);
            }
            else
                return;


            //tmp.Values["Custom 1"] = xmldoc.ToString();

            //StringBuilder sb = new StringBuilder();
            //TextWriter tr = new StringWriter(sb);
            //xmldoc.Save(tr);
            //tmp.Values["Custom 1"] = sb.ToString();
            tmp.SaveCustom(xmldoc);

            //var it = folder.NewItem();
            //var its="("+comboBox4.Text+")";
            //foreach(var t in folder.GetParents())
            //    its+=@"/"+t.Title;
            //it.Values["Title"] = its;
            //it.Values["Place Published"] = folder.UID;

            //folder.AddItem(it);

            //tmp = it;
            //str = tmp.Values["Custom 1"];

            //xmldoc = null;
            //if (str != null && str != string.Empty)
            //{
            //    var tr2 = new StringReader(str);
            //    xmldoc = XDocument.Load(tr2);
            //}
            //else
            //    xmldoc = new XDocument(new XDeclaration("1.0", "utf-16", "yes"), new XElement("NEUT"));

            //xmle = xmldoc.Root.Element("ReadHistory");
            //if (xmle == null)
            //{
            //    xmle = new XElement("ReadHistory", new XElement(comboBox4.Text));
            //    xmldoc.Root.Add(xmle);
            //}
            //else if (xmle.Element(comboBox4.Text) == null)
            //{
            //    xmle.Add(new XElement(comboBox4.Text));
            //}


            //tmp.Values["Custom 1"] = xmldoc.ToString();

            //sb = new StringBuilder();
            //tr = new StringWriter(sb);
            //xmldoc.Save(tr);
            //tmp.Values["Custom 1"] = sb.ToString();
        }


        private void button58_Click(object sender, EventArgs e)
        {
            var folder = textBox23.Tag.ToNEFolder();
            var doc = folder.GetRelatedItem().GetCustom();
            XElement xmle = doc.Root.Element("ReadHistory");
            if (xmle == null)
            {
                xmle = new XElement("ReadHistory");

                doc.Root.Add(xmle);
            }
            var tmp1 = xmle.Element(comboBox4.Text);
            if (tmp1 == null)
            {
                tmp1 = new XElement(comboBox4.Text);
                xmle.Add(tmp1);
            }
            xmle = tmp1;

            var items = folder.ParentLibrary.Parent.SelectedItems;
            for (var i = 0; i < items.Count; i++)
            {
                var tmp = items.get_Items(i);
                xmle.Add(new XElement("Item", tmp.UID));
            }

            folder.GetRelatedItem().SaveCustom(doc);

            /*
            var dt = DateTime.Now.ToString();
            var ser = new System.Xml.Serialization.XmlSerializer(typeof(SerializableDictionary<string, string>));
            StringBuilder sb = new StringBuilder();
            SerializableDictionary<string, string> list;
            var ne2 = new NoteExpress.NEHost2();
            var items = ne2.Libraries.SelectedItems;
            var folder = ne2.Libraries.ActiveFolder;
            var tmp = folder.GetRelatedItem();
            var str = tmp.Values["Custom 1"];
            if (str != null && str != string.Empty)
            {
                var sr = new StringReader(str);
                list = (SerializableDictionary<string, string>)ser.Deserialize(sr);
            }
            else
                list = new SerializableDictionary<string, string>();

            for (var i = 0; i < items.Count; i++)
            {
                var t = items.get_Items(i).Values["ID"];
                if (!list.Keys.Contains(t))
                    list.Add(t, dt);
                else
                    list[t] = dt;
            }

            StringWriter sw = new StringWriter(sb);
            ser.Serialize(sw, list);
            sw.Flush();

            tmp.Values["Abstract"] = dt;
            tmp.Values["Custom 1"] = sb.ToString();
             * */
        }

        private void button59_Click(object sender, EventArgs e)
        {

            var folder = textBox23.Tag.ToNEFolder();
            var tmp = folder.GetRelatedItem();
            var doc = tmp.GetCustom();
            var xml = doc.Root.Element("ReadHistory").Element(comboBox4.Text);

            var uids = (from i in xml.Elements() select i.Value).ToArray();

            var subf = folder.GetSubFolder("未处理-" + comboBox4.Text);
            if (subf == null) subf = folder.Add("未处理-" + comboBox4.Text);
            folder.Activate();


            var items = folder.Items;
            for (var i = 0; i < items.Count; i++)
            {
                var item = items.get_Items(i);
                if (tmp.UID == item.UID) continue;

                if (!uids.Contains(item.UID)) subf.LinkItem(item);


            }

            /*
            var ser = new System.Xml.Serialization.XmlSerializer(typeof(SerializableDictionary<string, string>));
            StringBuilder sb = new StringBuilder();
            SerializableDictionary<string, string> list;
            var ne2 = new NoteExpress.NEHost2();
            var folder = ne2.Libraries.ActiveFolder;
            var tmp = folder.GetRelatedItem();
            var str = tmp.Values["Custom 1"];
            if (str != null && str != string.Empty)
            {
                var sr = new StringReader(str);
                list = (SerializableDictionary<string, string>)ser.Deserialize(sr);

                var form = new ItemInfo();
                form.Tag = folder;
                var items = folder.Items;
                for (var i = 0; i < items.Count; i++)
                {
                    var item = items.get_Items(i);
                    if (item.UID == tmp.UID) continue;
                    var id = item.Values["ID"];
                    var row = new ListViewItem(id);
                    row.SubItems.Add(item.Values["Year"]);
                    //row.SubItems.Add(id);
                    if (list.Keys.Contains(id))
                        row.SubItems.Add(list[id]);
                    else
                        row.SubItems.Add(DateTime.MinValue.ToString());
                    form.listView1.Items.Add(row);
                }

                form.Show();
            }
             * */
        }



        private void button35_Click(object sender, EventArgs e)
        {
            var ne = new NoteExpress.NEHost2();
            var workItem = ne.Libraries.SelectedItems.FirstItem();
            var tmp = "<"+workItem.get_Values("ID") + "-" + workItem.get_Values("Year")+">";
            Clipboard.SetText(tmp);

            this.WindowState = FormWindowState.Minimized;
        }
        INEFolder backFolder;
        private void button36_Click(object sender, EventArgs e)
        {
            //if (backFolder != null)
            //    backFolder.Activate();
            //FolderHistory.Back();
        }
        private void button15_Click_1(object sender, EventArgs e)
        {
            var folder = textBox23.Tag.ToNEFolder();
            var tmp = folder.GetRelatedItem();
            var doc = tmp.GetCustom();
            var xml = doc.Root.Element("ReadHistory").Element(comboBox4.Text);
            var uids = (from i in xml.Elements() select i.Value).ToArray();

            var subf = folder.GetSubFolder("已处理-" + comboBox4.Text);
            if (subf == null) subf = folder.Add("已处理-" + comboBox4.Text);
            folder.Activate();

            var items = folder.Items;
            for (var i = 0; i < items.Count; i++)
            {
                var item = items.get_Items(i);
                if (tmp.UID == item.UID) continue;
                if (uids.Contains(item.UID)) subf.LinkItem(item);
            }
            /*
            //workItem = GetSelectedItem();
            var item = ne.Libraries.SelectedItems.FirstItem();

            var ser = new System.Xml.Serialization.XmlSerializer(typeof(SerializableDictionary<string, string>));
            StringBuilder sb = new StringBuilder();
            SerializableDictionary<string, string> list;
            var ne2 = new NoteExpress.NEHost2();
            var folder = ne2.Libraries.ActiveFolder;
            var tmp = folder.GetRelatedItem();
            if (tmp == null) return;
            var str = tmp.Values["Custom 1"];
            if (str != null && str != string.Empty)
            {
                var sr = new StringReader(str);
                list = (SerializableDictionary<string, string>)ser.Deserialize(sr);

                if (list.Keys.Contains(item.Values["ID"]))
                    toolStripStatusLabel1.Text = @"状态：已处理 " + list[item.Values["ID"]];
                else
                    toolStripStatusLabel1.Text = @"状态：未处理";
            }
             * */
        }
        private void button37_Click(object sender, EventArgs e)
        {
            var ne = new NoteExpress.NEHost2();
            var workItem = ne.Libraries.SelectedItems.FirstItem();
            if (workItem == null) return;
            var tmp = ">>>>>>>>>>\r\nTitle:" + workItem.get_Values("Title") + "\r\n" +
               "Authors:" + workItem.get_Values("Author") + "\r\n" +
            "Source:" + workItem.get_Values("Journal") + "," + workItem.get_Values("Year") + "\r\n" +
            "Abstract:" + "\r\n" + workItem.get_Values("Abstract") + "\r\n<<<<<<<<<<";
            Clipboard.SetText(tmp);
            this.WindowState = FormWindowState.Minimized;
        }

        private void button27_Click(object sender, EventArgs e)
        {
            var tmp = DateTime.Now.ToString();
            Clipboard.SetText(tmp);
        }

        //
        INEFolder folder12;
        private void button12_Click_1(object sender, EventArgs e)
        {
            folder12 = ne.Libraries.ActiveFolder;
            textBox24.Text = folder12.Title;
        }

        void DeleteItem(INEFolder folder1, INEFolder folder2, bool bStart = true)
        {
            if (folder1.UID == folder2.UID)
                return;
            //if (!bStart && folder2.Title[0] == '*') 
            folder1.DeleteItems(folder2.Items, false);
            for (int i = 0; i < folder2.Count; i++)
            {
                var tmp = folder2.get_Children(i);
                if (bStart && tmp.Title[0] == '*') continue;
                DeleteItem(folder1, tmp, bStart);
            }
        }

        void DeleteItem3(INEFolder folder1, INEFolder folder2, bool bStart = true)
        {
            if (folder1.UID == folder2.UID)
                return;
            if (!folder2.Title.StartsWith("*") || folder2.Title=="*not")
                folder1.DeleteItems(folder2.Items, false);
            for (int i = 0; i < folder2.Count; i++)
            {
                var tmp = folder2.get_Children(i);
                if (bStart && tmp.Title.StartsWith( "*")) continue;
                DeleteItem(folder1, tmp, bStart);
            }
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = @"工作中……";

            var thread = new Thread(new ThreadStart(
                () =>
                {
                    if (radioButton6.Checked)
                    {
                        var tmp = folder12.Add("未分类");
                        if (tmp != null)
                        {
                            tmp.LinkItems(folder12.Items);
                            for (int i = 0; i < folder12.Count; i++)
                            {
                                toolStripStatusLabel1.Text = @"工作中……" + i.ToString() + "/" + folder12.Count.ToString();
                                DeleteItem3(tmp, folder12.get_Children(i), checkBox10.Checked);
                            }

                            toolStripStatusLabel1.Text = @"工作完成！";
                        }
                        else
                            toolStripStatusLabel1.Text = @"错误！";
                    }
                    else
                    {
                        for (int i = 0; i < folder12.Count; i++)
                        {
                            toolStripStatusLabel1.Text = @"工作中……" + i.ToString() + "/" + folder12.Count.ToString();
                            DeleteItem3(folder12, folder12.get_Children(i), checkBox10.Checked);
                        }
                        toolStripStatusLabel1.Text = @"工作完成！";
                    }

                    if (checkBox16.Checked)
                    {
                        var folders = folder12.GetParents();
                        foreach (var t in folders)
                        {
                            var i = t.GetSubFolder("*not");
                            if (i != null)
                                folder12.DeleteItems(i.Items, false);
                        }

                    }
                }));
            thread.Start();
        }
        /*
        private void button15_Click_1(object sender, EventArgs e)
        {
            var str = "Note2:\r\nO=" + textBox25.Text + "\r\nM=" + textBox26.Text + "\r\n#\r\n";
            Clipboard.SetText(str);

            textBox25.Text = "";
            textBox26.Text = "";
            this.WindowState = FormWindowState.Minimized;
        }
        */
        //
        /*
        INEItem objitemzt;

        private void button18_Click_2(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = @"";
            objitemzt = ne.Libraries.SelectedItems.get_Items(0);
            textBox27.Text = objitemzt.get_Values("Title");
            textBox28.Text = objitemzt.get_Values("Category");
        }

        private void button21_Click_2(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = @"工作中……";

            var thread = new Thread(new ThreadStart(
                () =>
                {
                    objitemzt.set_Values("Category", textBox28.Text);
                    //XElement refs = XElement.Parse(ne.Internals.GetSelectedReferences());
                    //var selrefid = (from t in refs.Elements()
                    //                select t.Element("UID").Value).ToArray();


                    //for (int i = 0; i < ne.Libraries.ActiveFolder.Items.Count;i++ )
                    //{
                    //    var item = ne.Libraries.ActiveFolder.Items.get_Items(i);
                    //    if (selrefid.Contains(item.get_Values("_subject")))
                    //        item.set_Values("_subject", "");
                    //}

                    //objitemzdy.set_Values("Author Address", textBox21.Text);

                    //textBox16.Text = "";

                    toolStripStatusLabel1.Text = @"工作完成！";
                    //textBox15.Text = "";
                }));
            thread.Start();
        }
        */
        //SFX
        public class Item
        {
            public INEItem item
            {
                get;
                set;
            }

            public string get_Values(string str)
            {
                return item.get_Values(str);
            }
        }

        //private void button38_Click(object sender, EventArgs e)
        //{
        //    var url = @"http://scholar.google.com/scholar?&hl=zh-CN&q=";
        //    var ne = new NoteExpress.NEHost2();
        //    for (int i = 0; i < ne.Libraries.SelectedItems.Count; i++)
        //    {
        //        var item = ne.Libraries.SelectedItems.get_Items(i);
        //        try
        //        {
        //            var tmp = url + item.get_Values("title").Replace(" ", "+");
        //            System.Diagnostics.Process.Start(tmp);
        //            Thread.Sleep(100);
        //        }
        //        catch (System.Exception ex)
        //        {
        //            MessageBox.Show(ex.ToString());
        //        }
        //    }
        //}

        private void button21_Click_1(object sender, EventArgs e)
        {
            DirectoryInfo TheFolder = new DirectoryInfo(".\\search");
            Process.Start(TheFolder.FullName);
        }

        private void button33_Click_1(object sender, EventArgs e)
        {
            var py = cbEngine.SelectedItem as ComboBoxItem;
            Process.Start("notepad.exe", py.Value);
        }


        private void btSearch_Click(object sender, EventArgs e)
        {
            var py = cbEngine.SelectedItem as ComboBoxItem;
            var ipy = Python.CreateRuntime();
            dynamic t = ipy.UseFile(py.Value);
            var ne = new NoteExpress.NEHost2();
            for (int i = 0; i < ne.Libraries.SelectedItems.Count; i++)
            {
                var item = ne.Libraries.SelectedItems.get_Items(i);
                try
                {
                    var url = t.SearchUrl(new Item() { item = item });
                    System.Diagnostics.Process.Start(url);
                    Thread.Sleep(100);
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

        ///==============
        private void button39_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("explorer.exe", Application.StartupPath);
        }

        private void btReset_Click(object sender, EventArgs e)
        {
            Application.Restart();
        }

        // 分析
        INEFolder FolderAnaylysis;
        private void btn分析选择_Click(object sender, EventArgs e)
        {
            FolderAnaylysis = ne.Libraries.ActiveFolder;
            tbAnalysis.Text = FolderAnaylysis.Title;
        }

        void GetAllItems(INEFolder folder, bool iterate, ref List<INEItem> rt)
        {
            if (rt.Count != 0 && checkBox13.Checked && folder.Title.IndexOf("*") == 0) return;

            for (var i = 0; i < folder.Items.Count; i++)
            {
                var tmp = folder.Items.get_Items(i);
                if (!rt.Contains(tmp))
                    rt.Add(tmp);
            }
            if (iterate)
                for (var i = 0; i < folder.Count; i++)
                {
                    GetAllItems(folder.get_Children(i), iterate, ref rt);
                }
        }
        neut.FolderAnalysis.FolderTree Foldertree;
        private void btn分析_Click(object sender, EventArgs e)
        {
            var thread = new Thread(() =>
            {
                toolStripStatusLabel1.Text = @"工作中……！";
                var items = new List<INEItem>();

                //toolStripStatusLabel1.Text = @"遍历题录";
                GetAllItems(FolderAnaylysis, cb分析遍历子文件夹.Checked, ref items);

                var dir = new Dictionary<string, List<INEItem>>();
                foreach(INEItem t1 in items)
                {                    
                    foreach (var t2 in t1.GetPaths())
                    {
                        if (dir.ContainsKey(t2))
                            dir[t2].Add(t1);
                        else
                        {
                            var tmp = new List<INEItem>();
                            tmp.Add(t1);
                            dir.Add(t2, tmp);
                        }
                    }
                }                        

                Foldertree = new FolderAnalysis.FolderTree();

                Foldertree.Load += (a, b) =>
                {
                    toolStripStatusLabel1.Text = @"工作完成！";
                };

                //toolStripStatusLabel1.Text = @"生成节点";
                Foldertree.Sum = items.Count;
                Foldertree.TopMost = true;
                for (var t = 0; t < items.Count; t++)
                {
                    Foldertree.AddNode(items[t], checkBox13.Checked);
                    toolStripStatusLabel1.Text = @"工作中……" + ((t + 1) / (double)(items.Count) * 100).ToString("##") + "%！";
                }

                //toolStripStatusLabel1.Text = @"显示节点树";
                Foldertree.ShowDialog();


            });
            thread.IsBackground = true;

            thread.Start();
        }
        ///=======
        /// 
        private void button25_Click(object sender, EventArgs e)
        {
            var ne = new NoteExpress.NEHost2();
            var items = ne.Libraries.SelectedItems;
            for (var i = 0; i < items.Count; i++)
            {
                var tmp = items.get_Items(i).AttachmentFiles;
                foreach (var t in tmp.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    Process.Start(t);
                }
            }
        }
        private void button76_Click(object sender, EventArgs e)
        {
            var dlg = new FolderBrowserDialog();
            if (dlg.ShowDialog() != DialogResult.OK)
                return;

            var ne = new NoteExpress.NEHost2();
            var folder = ne.Libraries.ActiveFolder.GetFullName();
            if (folder.StartsWith("\\Recent Searches"))
            {
                folder = dlg.SelectedPath + "\\" + ne.Libraries.ActiveFolder.Title;
            }
            else
            {
                folder = folder.Substring(12, folder.Length - 13).Replace("\\", "~");
                folder = dlg.SelectedPath + "\\" + folder;
            }
            System.IO.Directory.CreateDirectory(folder);

            var items = ne.Libraries.SelectedItems;
            for (var i = 0; i < items.Count; i++)
            {
                var tmp = items.get_Items(i).AttachmentFiles;
                foreach (var t in tmp.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    var finof = new FileInfo(t);
                    System.IO.File.Copy(t, folder + "\\"+finof.Name,true);
                }
            }
        }
        INEFolder GetAjiFolder()
        {
            var ne = new NEHost2();
            var AjiFolder = ne.Libraries.ActiveFolder.ParentLibrary.References.GetSubFolder("Aji Synchro");
            if (AjiFolder == null)
            {
                AjiFolder = ne.Libraries.ActiveFolder.ParentLibrary.References.GetFolder2("Aji Synchro");
                AjiFolder.GetFolder2("Output");
                AjiFolder.GetFolder2("UnProcessed");
            }
            return AjiFolder;
        }
        private void button34_Click_1(object sender, EventArgs e)
        {
            //var dlg=new FolderBrowserDialog();
            //if(dlg.ShowDialog()!=DialogResult.OK)
            //    return;
            var ne = new NoteExpress.NEHost2();
            if (ne.Libraries.ActiveFolder.UID == ne.Libraries.ActiveFolder.ParentLibrary.References.UID)
            {
                Log.Writeline("Items in Root can not be output pdfs.");
                return;
            }

            var AjiFolder = GetAjiFolder();

            var folder = ne.Libraries.ActiveFolder.GetFullName();

            if (folder.StartsWith("\\Recent Searches"))
            {
                folder = textBox8.Text + "\\" + ne.Libraries.ActiveFolder.Title;
            }
            else
            {
                folder = folder.Substring(12, folder.Length - 13).Replace("\\", "~");
                folder = textBox8.Text + "\\" + folder;
            }

            System.IO.Directory.CreateDirectory(folder);
            var items = ne.Libraries.SelectedItems;
            for (var i = 0; i < items.Count; i++)
            {
                var tmp = items.get_Items(i).AttachmentFiles;
                foreach (var t in tmp.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    var name = items.get_Items(i).Values["Title"];
                    name = name.Replace(":", " ");
                    var str = folder + "\\" + items.get_Items(i).Values["ID"] + "-" + name + ".pdf";

                    if (t.ToLower().LastIndexOf(".pdf") == (t.Length - 4))
                    {
                        if (System.IO.File.Exists(str))
                        {
                            Log.Writeline(items.get_Items(i).Values["ID"] + " is already in output folder.");
                            System.IO.File.Delete(str);
                        }
                        System.IO.File.Copy(t, str);
                    }
                }
            }

            AjiFolder.GetSubFolder("Output").LinkItems(items);
            toolStripStatusLabel1.Text = "导出完成";
        }


        private void button40_Click(object sender, EventArgs e)
        {
            (new NoteExpress.NEHost2()).Libraries.ActiveFolder.GetRelatedItem();
        }

        /// <summary>
        INEItems clip;
        string clipfolder;
        private void button41_Click(object sender, EventArgs e)
        {
            if (radioButton3.Checked)
            {
                clip = ne.Libraries.SelectedItems;
                if (clip != null)
                {
                    ne.Libraries.ActiveFolder.DeleteItems(clip, false);
                }
            }
            else
            {
                clipfolder = ne.Libraries.ActiveFolder.Title;
                clip = ne.Libraries.ActiveFolder.GetItems().ToItems();
                //   ne.Libraries.ActiveFolder.GetParent().d
            }
        }

        private void button42_Click(object sender, EventArgs e)
        {
            if (radioButton3.Checked)
            {
                clip = ne.Libraries.SelectedItems;
            }
            else
            {
                clipfolder = ne.Libraries.ActiveFolder.Title;
                clip = ne.Libraries.ActiveFolder.GetItems().ToItems();
            }
        }

        private void button43_Click(object sender, EventArgs e)
        {
            if (radioButton3.Checked)
            {
                if (clip != null)
                    ne.Libraries.ActiveFolder.LinkItems(clip);
            }
            else
            {
                var foldertmp = ne.Libraries.ActiveFolder.Add(clipfolder);
                foldertmp.LinkItems(clip);
            }
        }

        //==============
        private void button45_Click_1(object sender, EventArgs e)
        {
            var ne = new NoteExpress.NEHost2();
            var item = ne.Libraries.ActiveFolder;
            textBox13.Text = item.Title;
            textBox13.Tag = item;
        }


        private void button44_Click(object sender, EventArgs e)
        {
            var ne = new NoteExpress.NEHost2();
            var item = ne.Libraries.SelectedItems.FirstItem();
            textBox30.Text = item.Values["ID"] + "," + item.Values["Title"];
            textBox30.Tag = item;
            RefreshCiting(item);
            RefreshButton();

            //string str = textBox30.Tag.ToNEItem().Values["Cited Count"];
            //if (str != null && str != string.Empty)
            //{
            //    var tmp = str.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
            //    if (tmp.Length < 2) textBox15.Text = str;
            //    else textBox15.Text = tmp[0];
            //}
            //else
            //    textBox15.Text = "";
            //RefreshCitedID(textBox30.Tag.ToNEItem());
            toolStripStatusLabel1.Text = @"Refreshed Citing！";
        }
        INEItems subs;
        private void button45_Click(object sender, EventArgs e)
        {
            subs = ne.Libraries.SelectedItems;
            textBox13.Text = subs.Count == 1 ? subs.Items[0].Values["Title"] : (subs.Count.ToString() + " items");
            toolStripStatusLabel1.Text = @"";

        }

        //private void button46_Click(object sender, EventArgs e)
        //{
        //    var t0 = ne.Libraries.ActiveFolder;
        //    if (textBox30.Tag == null) return;
        //    var obj = (INEItem)textBox30.Tag;
        //    var tmp = obj.GetRelatedFolder();
        //    if (tmp == null) tmp = obj.CreateRelatedFolder();
        //    tmp.LinkItem(obj);
        //    if (radioButton12.Checked)
        //        tmp.GetSubFolder("Citing").LinkItems(subs);
        //    else
        //        tmp.GetSubFolder("Cited").LinkItems(subs);
        //    t0.Activate();
        //    toolStripStatusLabel1.Text = @"Adding Finished！";
        //    RefreshButton();
        //    textBox13.Text = "";
        //    textBox13.Tag = null;
        //    //RefreshCitedID(textBox30.Tag.ToNEItem());
        //}

        private void button47_Click(object sender, EventArgs e)
        {
            if (textBox30.Tag == null) return;
            var item = (INEItem)textBox30.Tag;
            var tmp = item.GetRelatedFolder();
            if (tmp == null)
                toolStripStatusLabel1.Text = @"No Citing！";
            else
            {
                var t = tmp.GetSubFolder("Citing");
                if (t.Items.Count == 0) toolStripStatusLabel1.Text = @"No Citing！";
                else
                {
                    //t.Activate();
                    t.AddInHistory().Activate();
                    toolStripStatusLabel1.Text = @"Citing Open！";
                }
            }
            (new NEHost2()).MainForm.Show();
        }

        //void RefreshCitedID(INEItem item)
        //{
        //    comboBox3.Items.Clear();
        //    if (textBox30.Tag == null) return;
        //    var cited=textBox30.Tag.ToNEItem().GetCited();
        //    if(cited!=null)
        //    foreach (var t in cited)
        //    {
        //        comboBox3.Items.Add(new BoxItem<INEItem>(t.Values["ID"],t));
        //    }
        //}

        void RefreshCiting(INEItem item)
        {
            toolStripStatusLabel1.Text = @"Refresh Citing！";
            var r = item.GetRelatedFolder();
            foreach (var f in item.GetPaths())
            {
                if (f.IndexOf("@Relation") > -1 && f.IndexOf("Citing") > -1)
                {
                    if (r == null)
                    {
                        r = item.CreateRelatedFolder();
                    }
                    var id = f.ToNEFolder().Parent.Title;
                    var obj = r.ParentLibrary.References.GetSubFolder("@Relation").GetSubFolder(id).FindItemFromID(id);
                    r.GetSubFolder("Citing").LinkItem(obj);
                }
            }
        }

        void RefreshButton()
        {
            if (textBox30.Tag == null) return;

            var tmp = ((INEItem)textBox30.Tag).GetRelatedFolder();
            if (tmp != null)
            {
                button47.Text = "Go Citing (" + tmp.GetSubFolder("Citing").Items.Count.ToString() + ")";
                button48.Text = "Go Cited (" + tmp.GetSubFolder("Cited").Items.Count.ToString() + ")";
            }
            else
            {
                button47.Text = "Go Citing";// +tmp.GetSubFolder("Citing").Items.Count.ToString() + ")";
                button48.Text = "Go Cited";// +tmp.GetSubFolder("Cited").Items.Count.ToString() + ")";
            }
        }

        private void button48_Click(object sender, EventArgs e)
        {
            if (textBox30.Tag == null) return;
            var item = (INEItem)textBox30.Tag;
            var tmp = item.GetRelatedFolder();
            if (tmp == null)
                toolStripStatusLabel1.Text = @"No Cited！";
            else
            {
                var t = tmp.GetSubFolder("Cited");
                if (t.Items.Count == 0) toolStripStatusLabel1.Text = @"No Cited！";
                else
                {
                    //t.Activate();
                    t.AddInHistory().Activate();
                    toolStripStatusLabel1.Text = @"Cited Open！";
                }
            }
            (new NEHost2()).MainForm.Show();
        }

        void AddItem(INEItem item, Dictionary<INEItem, List<INEItem>[]> arr)
        {
            if (arr.Keys.Find(item) != null) return;
            var n = new List<INEItem>[] { new List<INEItem>(), new List<INEItem>() };
            arr.Add(item, n);

            var t2 = item.GetCiting();
            if (t2 != null)
            {
                foreach (var t in t2)
                {
                    if (n[1].Find(t) != null) continue;
                    else n[1].Add(t);
                    AddItem(t, arr);
                    var tt = arr.Keys.Find(t);
                    if (tt != null && arr[tt][0].Find(item) == null) arr[tt][0].Add(item);
                }
            }

            var t1 = item.GetCited();
            if (t1 != null)
            {
                foreach (var t in t1)
                {
                    if (n[0].Find(t) != null) continue;
                    else n[0].Add(t);
                    AddItem(t, arr);
                }
            }

        }

        private void button71_Click(object sender, EventArgs e)
        {
            var folder = textBox13.Tag.ToNEFolder();
            var arr = new Dictionary<INEItem, List<INEItem>[]>();
            var items = folder.GetItems(checkBox15.Checked);
            var i = 0;
            foreach (var t in items)
            {
                toolStripStatusLabel1.Text = t.Values["ID"] + @" 工作中……" + (i++ * 100 / items.Count()) + "%";
                AddItem(t, arr);
            }

            var list = arr.OrderBy((t) =>
                {
                    return t.Value[0].Count;
                }).Reverse();
            Log.Writeline("Cited Rank:");
            foreach (var t in list)
            {
                Log.Writeline(t.Key.Values["ID"] + ": " + t.Value[0].Count + " " + t.Value[1].Count);
            }

            return;
            /*
            var app = new Visio.Application();
            //app.Visible = false; 
            var doc = app.Documents.Add("basicd_m.vst");

            foreach (var t in arr)
            {
                if (t.Value[0].Count < 1) continue;
               app.CreateBlock(t.Key.get_Values("ID"), t.Key.get_Values("ID"));
            }
            foreach (var t in arr)
            {
                if (t.Value[0].Count < 1) continue;
                var t1 = (Visio.Shape)app.ActiveWindow.Page.Shapes.Item(t.Key.Values["ID"]);
                foreach (var tt in t.Value[1])
                {
                    var t2 = (Visio.Shape)app.ActiveWindow.Page.Shapes.Item(tt.Values["ID"]);
                    app.ConnectShapes(t1, t2);
                }
            }

            app.ActiveWindow.Page.Layout();
             * */
        }

        private void button50_Click(object sender, EventArgs e)
        {
            if (comboBox3.Text == null) return;

            ((BoxItem<INEItem>)comboBox3.SelectedItem).Tag.OpenAttachFile();
            toolStripStatusLabel1.Text = @"Cited item attach file opened";
        }


        private void button51_Click(object sender, EventArgs e)
        {
            if (comboBox3.Text == string.Empty) return;

            this.WindowState = FormWindowState.Minimized;

            var tmp = (BoxItem<INEItem>)comboBox3.SelectedItem;
            bool btmp;
            ne.Internals.EditReference(ne.Libraries.ActiveFolder.ParentLibrary.UID, tmp.Tag.UID, out btmp);
            toolStripStatusLabel1.Text = @"Cited item opened";
        }
        //==========
        private void button55_Click(object sender, EventArgs e)
        {
            button18_Click_1(this, null);

            var ne = new NoteExpress.NEHost2();
            var t0 = ne.Libraries.ActiveFolder;
            t0.AddInHistory();
            var item = ne.Libraries.SelectedItems.FirstItem();
            textBox17.Text = item.Values["ID"] + "," + item.Values["Title"];
            textBox17.Tag = item;
            RefreshCiting(item);
            toolStripStatusLabel1.Text = @"Refreshed Citing！";

            RefreshNoList();
        }

        private void button56_Click(object sender, EventArgs e)
        {
            var ne2 = new NoteExpress.NEHost2();
            var item = ne.Libraries.SelectedItems.FirstItem();
            RefNo.Tag = item;
            textBox16.Text = item.Values["Year"];
            textBox18.Text = item.Values["Title"];
            toolStripStatusLabel1.Text = @"Selected a item！";
        }

        private void button57_Click(object sender, EventArgs e)
        {
            var t0 = ne.Libraries.ActiveFolder;
            var f = textBox17.Tag.ToNEItem().GetRelatedFolder();
            if (f == null) f = textBox17.Tag.ToNEItem().CreateRelatedFolder();
            f = f.GetSubFolder("Citing");
            var item = f.NewItem();
            f.AddItem(item);
            RefNo.Tag = item;
            item.Values["Year"] = textBox16.Text;
            //textBox16.Text = "";
            item.Values["Title"] = textBox18.Text.Replace("\r\n", "");
            //textBox18.Text = "";
            toolStripStatusLabel1.Text = @"Added a item！";
            button54_Click(this, null);
            t0.Activate();
        }

        private void button52_Click(object sender, EventArgs e)
        {
            // Declares an IDataObject to hold the data returned from the clipboard.
            // Retrieves the data from the clipboard.
            IDataObject iData = Clipboard.GetDataObject();

            // Determines whether the data is in a format you can use.
            if (iData.GetDataPresent(DataFormats.Text))
            // Yes it is, so display it in a text box.
            {
                var txt = (String)iData.GetData(DataFormats.Text);
                if (txt == string.Empty) return;
                var ipy = Python.CreateRuntime();
                dynamic t = ipy.UseFile("ReplaceBlankScrip.py");
                txt = t.ReplaceBlank(txt);
                txt = txt.Trim();
                var m = Regex.Matches(txt, @"^(\d+)");
                if (m.Count > 0)
                {
                    RefNo.Value = int.Parse(m[0].Value);
                }
                var ttt = new Regex(@"^\[(\d+)\]");
                if (ttt.IsMatch(txt))
                {
                    RefNo.Value = int.Parse(ttt.Match(txt).Groups[1].Value);
                }
                m = Regex.Matches(txt, @"(19|20)\d{2}");
                if (m.Count > 0)
                {
                    textBox16.Text = m[0].Value;
                }
                var tt = txt.Split(new char[] { ',', '.', '\"', '，', '“', '”', '(', ')', '[', ']' });
                var tmp = "";
                foreach (var t0 in tt)
                {
                    if (t0.Length > tmp.Length)
                        tmp = t0;
                }
                textBox18.Text = tmp.Trim();
            }
        }

        private void button53_Click(object sender, EventArgs e)
        {
            if (textBox17.Tag == null) return;
            var item = (INEItem)textBox17.Tag;
            var tmp = item.GetRelatedFolder();
            if (tmp == null)
                toolStripStatusLabel1.Text = @"No Citing！";
            else
            {
                var t = tmp.GetSubFolder("Citing");
                if (t.Items.Count == 0) toolStripStatusLabel1.Text = @"No Citing！";
                else
                {
                    //t.Activate();
                    t.AddInHistory().Activate();
                    toolStripStatusLabel1.Text = @"Citing Open！";
                }
            }
            (new NEHost2()).MainForm.Show();
        }

        private void button54_Click(object sender, EventArgs e)
        {
            if (textBox17.Tag == null) return;
            var rfolder = textBox17.Tag.ToNEItem().GetRelatedFolder();
            if (rfolder == null) rfolder = textBox17.Tag.ToNEItem().CreateRelatedFolder();
            rfolder.LinkItem(textBox17.Tag.ToNEItem());
            rfolder.GetSubFolder("Citing").LinkItem(RefNo.Tag.ToNEItem());

            var ser = new System.Xml.Serialization.XmlSerializer(typeof(SerializableDictionary<string, string>));
            StringBuilder sb = new StringBuilder();
            SerializableDictionary<string, string> list;
            var str = RefNo.Tag.ToNEItem().Values["Custom 1"];
            XDocument doc = null;
            if (str != null && str != string.Empty)
            {
                doc = XDocument.Parse(str);
                if (doc.Root.Element("Reference") != null)
                {
                    var sr = new StringReader(doc.Root.Element("Reference").Elements().First().ToString());
                    list = (SerializableDictionary<string, string>)ser.Deserialize(sr);
                }
                else
                    list = new SerializableDictionary<string, string>();
            }
            else
                list = new SerializableDictionary<string, string>();

            if (list.Keys.Contains(textBox17.Tag.ToNEItem().Values["ID"]))
                list[textBox17.Tag.ToNEItem().Values["ID"]] = RefNo.Text;
            else
                list.Add(textBox17.Tag.ToNEItem().Values["ID"], RefNo.Text);

            StringWriter sw = new StringWriter(sb);
            ser.Serialize(sw, list);
            sw.Flush();
            var tmp = XDocument.Parse(sw.ToString());

            if (str == null || doc.Root.Element("Reference") == null)
            {
                doc = new XDocument(new XDeclaration("1.0", "utf-16", "yes"), new XElement("NEUT"));
                var t = new XElement("Reference");
                t.Add(tmp.Root);
                doc.Root.Add(t);
            }
            else
                doc.Root.Element("Reference").ReplaceAll(tmp.Root);

            RefNo.Tag.ToNEItem().Values["Custom 1"] = doc.ToString();
            RefreshNoList();
            RefNo.UpButton();

            textBox16.Text = "";
            textBox18.Text = "";
        }

        void RefreshCitingID()
        {
            var item = textBox17.Tag.ToNEItem();
            var items = new Dictionary<string, BoxItem<INEItem>>();

            var items1 = item.GetCiting();
            if (items1 != null)
                foreach (var t in items1)
                {
                    items.Add(t.UID, new BoxItem<INEItem>(t.Values["title"], t));
                }
            var items2 = item.GetCitingFromPaths();
            if (items2 != null)
                foreach (var t in items2)
                {
                    if (items.Keys.Contains(t.UID)) continue;
                    items.Add(t.UID, new BoxItem<INEItem>(t.Values["title"], t));
                }
            comboBox2.DataSource = items.Values;
        }
        /*
        string GetNo(INEItem item,INEItem refitem)
        {
            var rf = item.GetRelatedFolder();
            if (rf == null) return null;
            var items = rf.GetSubFolder("Citing").Items;
            for (var i = 0; i < items.Count; i++)
            {
                var t = items.get_Items(i);
                var str = t.Values["Custom 1"];

                if (str != null && str.IndexOf("<") < 0)
                {
                    if (DialogResult.Yes == MessageBox.Show(item.Values["ID"] + ": Custom 1 被占用！是否清空", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                        t.Values["Custom 1"] = "";
                    else continue;
                }

                var ser = new System.Xml.Serialization.XmlSerializer(typeof(SerializableDictionary<string, string>));
                StringBuilder sb = new StringBuilder();
                SerializableDictionary<string, string> list;

                if (str != null && str != string.Empty)
                {
                    var sr = new StringReader(str);
                    list = (SerializableDictionary<string, string>)ser.Deserialize(sr);
                    if (list.Keys.Contains(item.Values["ID"]))
                    {
                        return list[item.Values["ID"]];
                    }
                }
            }
            return null;
        }
        */
        void RefreshNoList()
        {
            if (textBox17.Tag == null) return;
            comboBox1.Items.Clear();
            comboBox2.Items.Clear();

            var item = textBox17.Tag.ToNEItem();
            INEItem[] items = null;
            var items1 = item.GetCiting();
            var items2 = item.GetCitingFromPaths();

            if (items1 != null && items2 != null)
                items = items1.AddUnique(items2);
            else if (items2 != null)
                items = items2;
            else if (items1 != null)
                items = items1;

            foreach (var t in items)
            {
                var no = item.GetCtingNo(t);
                if (no != string.Empty)
                {
                    comboBox1.Items.Add(new BoxItem<INEItem>(no, t));
                }
            }

            if (checkBox8.Checked)
                items = items.Mutual(ne.Libraries.ActiveFolder.GetItems());

            foreach (var t in items)
            {
                comboBox2.Items.Add(new BoxItem<INEItem>(t.Values["ID"], t));
            }
            /*
            comboBox3.Items.Clear();
            //comboBox3.DataSource = items.Values.ToList();
            foreach (var t in items)
            {
                comboBox3.Items.Add(new BoxItem<INEItem>(t.Values["ID"], t));
            }
            ==
            var rf = textBox17.Tag.ToNEItem().GetRelatedFolder();
            if (rf == null) return;
            var items = rf.GetSubFolder("Citing").Items;
            for (var i = 0; i < items.Count; i++)
            {
                var item = items.get_Items(i);

                var str = item.Values["Custom 1"];

                if (!checkBox8.Checked)
                        comboBox2.Items.Add(new BoxItem<INEItem>(item.Values["ID"], item));

                var no = textBox17.Tag.ToNEItem().GetCtingNo(item);
                    if (no!=string.Empty)
                    {
                        comboBox1.Items.Add(new BoxItem<INEItem>(no, item));
                    }

            }

            if (checkBox8.Checked)            
                foreach (var t in FoldersShare(rf, false, rf.ParentLibrary.Parent.ActiveFolder, false))
                {
                    if (t.UID == textBox17.Tag.ToNEItem().UID) continue;
                    comboBox2.Items.Add(new BoxItem<INEItem>(t.Values["ID"], t));
                }
             * */
        }

        private void button28_Click(object sender, EventArgs e)
        {
            if (textBox17.Tag == null) return;
            this.WindowState = FormWindowState.Minimized;

            var tmp = (BoxItem<INEItem>)comboBox1.SelectedItem;
            bool btmp;
            var ne2 = new NEHost2();
            ne.Internals.EditReference(ne2.Libraries.ActiveFolder.ParentLibrary.UID, tmp.Tag.UID, out btmp);
            toolStripStatusLabel1.Text = @"Edit Item！";
        }

        private void button75_Click(object sender, EventArgs e)
        {
            if (textBox17.Tag == null) return;
            this.WindowState = FormWindowState.Minimized;

            var tmp = (BoxItem<INEItem>)comboBox1.SelectedItem;
            var ttt = ne.Libraries.ActiveFolder;
            var t = ne.Libraries.ActiveFolder.ParentLibrary.Notes.NewItem();
            t.Values["title"] = tmp.Tag.Values["Title"];
            ne.Libraries.ActiveFolder.ParentLibrary.Notes.AddItem(t);
            //bool btmp;
            //ne.Internals.EditReference(ne.Libraries.ActiveFolder.ParentLibrary.UID,t.UID, out btmp);
            ttt.Activate();
        }


        private void button29_Click(object sender, EventArgs e)
        {
            if (textBox17.Tag == null) return;

            var tmp = (BoxItem<INEItem>)comboBox1.SelectedItem;
            tmp.Tag.OpenAttachFile();
            toolStripStatusLabel1.Text = @"Opened Attach Files！";
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (textBox17.Tag == null) return;

            var item = (BoxItem<INEItem>)comboBox1.SelectedItem;
            textBox16.Text = item.Tag.Values["Year"];
            textBox18.Text = item.Tag.Values["Title"];
            RefNo.Text = comboBox1.SelectedItem.ToString();
            RefNo.Tag = item.Tag;

            comboBox2.Text = item.Tag.Values["ID"];
            comboBox2.Tag = item;
        }

        private void button23_Click(object sender, EventArgs e)
        {
            if (textBox17.Tag == null) return;
            this.WindowState = FormWindowState.Minimized;

            var tmp = (BoxItem<INEItem>)comboBox2.SelectedItem;
            bool btmp;
            var ne2 = new NEHost2();
            ne.Internals.EditReference(ne2.Libraries.ActiveFolder.ParentLibrary.UID, tmp.Tag.UID, out btmp);
            toolStripStatusLabel1.Text = @"Edit Item！";
        }

        private void button60_Click(object sender, EventArgs e)
        {
            if (textBox17.Tag == null) return;

            var tmp = (BoxItem<INEItem>)comboBox2.SelectedItem;
            tmp.Tag.OpenAttachFile();
            toolStripStatusLabel1.Text = @"Opened Attach Files！";
        }

        private void checkBox8_CheckedChanged(object sender, EventArgs e)
        {
            if (textBox17.Tag == null) return;
            comboBox2.Items.Clear();
            var rf = textBox17.Tag.ToNEItem().GetRelatedFolder();
            if (rf == null) return;
            var f = rf.GetSubFolder("Citing");
            var items = f.Items;

            if (!checkBox8.Checked)
                for (var i = 0; i < items.Count; i++)
                {
                    var item = items.get_Items(i);

                    comboBox2.Items.Add(new BoxItem<INEItem>(item.Values["ID"], item));
                }
            else
                foreach (var t in FoldersShare(f, false, f.ParentLibrary.Parent.ActiveFolder, false))
                {
                    comboBox2.Items.Add(new BoxItem<INEItem>(t.Values["ID"], t));
                }

        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (textBox17.Tag == null) return;

            var item = (BoxItem<INEItem>)comboBox2.SelectedItem;
            textBox16.Text = item.Tag.Values["Year"];
            textBox18.Text = item.Tag.Values["Title"];
            //RefNo.Text = GetNo(textBox17.Tag.ToNEItem(), item.Tag);
            comboBox1.Text = textBox17.Tag.ToNEItem().GetCtingNo(item.Tag);
            comboBox1.Tag = item.Tag;
            RefNo.Tag = item.Tag;
            toolStripStatusLabel1.Text = item.Tag.Values["Author"] + " " + item.Tag.Values["Year"] + " slected!";
        }
        //============被引
        private void button65_Click(object sender, EventArgs e)
        {
            var ne2 = new NEHost2();
            ne2.Libraries.ActiveFolder.AddInHistory();
            var item = ne2.Libraries.SelectedItems.FirstItem();
            textBox20.Text = item.Values["Author"] + "\r\n" + item.Values["Year"] + "\r\n" + item.Values["Title"];
            textBox20.Tag = item;
            RefreshCitedID();

        }

        private void button66_Click(object sender, EventArgs e)
        {
            var ne2 = new NEHost2();
            var item = ne2.Libraries.SelectedItems.FirstItem();
            textBox19.Text = item.Values["ID"] + "," + item.Values["Title"];
            textBox19.Tag = item;
        }

        private void button62_Click(object sender, EventArgs e)
        {
            var ne2 = new NEHost2();
            var item = textBox20.Tag.ToNEItem();
            var folder = item.GetRelatedFolder();
            if (folder == null) folder = item.CreateRelatedFolder();
            folder = folder.GetSubFolder("Cited");
            foreach (BoxItem<INEItem> t in comboBox3.Items)
            {
                folder.LinkItem(t.Tag);
            }
            folder.AddInHistory().Activate(); ;
            (new NEHost2()).MainForm.Show();
        }
        private void button61_Click(object sender, EventArgs e)
        {
            var ne2 = new NEHost2();
            var item = ne2.Libraries.SelectedItems.FirstItem();
            item.Values["Cited Count"] = textBox15.Text + " " + DateTime.Now.ToShortDateString();
        }
        private void button64_Click(object sender, EventArgs e)
        {
            var item = textBox20.Tag.ToNEItem();
            var folder = item.GetRelatedFolder();
            if (folder == null)
            {
                var folderto = textBox19.Tag.ToNEItem().GetRelatedFolder();
                if (folderto == null)
                    folderto = textBox19.Tag.ToNEItem().CreateRelatedFolder();
                folderto.GetSubFolder("Citing").LinkItem(item);
            }
            else
            {
                folder.GetSubFolder("Cited").LinkItem(textBox19.Tag.ToNEItem());
            }

            RefreshCitedID();
        }

        void RefreshCitedID()
        {
            var item = textBox20.Tag.ToNEItem();

            INEItem[] items = null;
            var items1 = item.GetCited();
            var items2 = item.GetCitedFromPaths();

            if (items1 != null && items2 != null)
                items = items1.AddUnique(items2);
            else if (items2 != null)
                items = items2;
            else if (items1 != null)
                items = items1;

            if (checkBox14.Checked)
                items = items.Mutual(ne.Libraries.ActiveFolder.GetItems());

            comboBox3.Items.Clear();
            //comboBox3.DataSource = items.Values.ToList();
            foreach (var t in items)
            {
                comboBox3.Items.Add(new BoxItem<INEItem>(t.Values["ID"], t));
            }
        }

        private void checkBox14_CheckedChanged(object sender, EventArgs e)
        {
            RefreshCitedID();
        }
        //===========
        void RefreshTree()
        {
            treeView1.Nodes.Clear();
            foreach (var path in button63.Tag.ToNEItem().GetPaths())
            {
                if (path.IndexOf("*") > -1) continue;
                var tmp0 = path.ToNEFolder();
                var node = treeView1.Nodes;
                var folders = tmp0.GetParents();
                for (var i = 0; i < folders.Length; i++)
                {
                    var tnode = node.IndexOfKey(folders[i].Title);

                    if (tnode < 0)
                    {
                        var tmp = new TreeNode(folders[i].Title);
                        tmp.Name = tmp.Text;
                        tmp.Tag = folders[i];
                        var n = node.Add(tmp);
                        node = node[n].Nodes;
                    }
                    else
                    {
                        node = node[tnode].Nodes;
                    }
                }
                var tnode0 = node.IndexOfKey(tmp0.Title);
                if (tnode0 < 0)
                {
                    var tmp = new TreeNode(tmp0.Title);
                    tmp.Name = tmp.Text;
                    tmp.Tag = tmp0;
                    var n = node.Add(tmp);
                    node = node[n].Nodes;
                }

            }

            treeView1.ExpandAll();
        }
        private void button63_Click(object sender, EventArgs e)
        {
            var ne2 = new NEHost2();
            var item = ne2.Libraries.SelectedItems.FirstItem();
            button63.Tag = item;

            RefreshTree();
        }

        //private void listBox1_DoubleClick(object sender, EventArgs e)
        //{
        //    var folder = listBox1.SelectedItem.ToString().ToNEFolder().Activate();
        //    ne.MainForm.Show();
        //}

        private void goToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeView1.SelectedNode.Tag.ToNEFolder().Activate();
            ne.MainForm.Show();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var form = new FoldersDlg();
            form.Location = new Point(this.Location.X - form.Width, this.Location.Y);

            form.NEFolder = treeView1.SelectedNode.Tag.ToNEFolder();
            form.NEItem = button63.Tag.ToNEItem();
            form.Show();
            form.FormClosed += (a, b) =>
                {
                    if (form.NEFolder != treeView1.SelectedNode.Tag.ToNEFolder())
                        RefreshTree();
                };
        }
        //====================
        private void button69_Click(object sender, EventArgs e)
        {
            textBox22.Text = ne.Libraries.ActiveFolder.Title;
            textBox22.Tag = ne.Libraries.ActiveFolder;
        }
        void ChangeXML(INEFolder folder)
        {
            for (var i = 0; i < folder.Items.Count; i++)
            {
                var item = folder.Items.get_Items(i);
                var txt = item.Values["Custom 1"];
                if (txt == null) continue;

                var doc = XDocument.Parse(txt);
                if (doc.Root.Name.LocalName == "SerializableDictionaryOfStringString")
                {
                    var t = new XElement("Reference");
                    t.Add(doc.Root);
                    doc = new XDocument(new XDeclaration("1.0", "utf-16", "yes"), new XElement("NEUT"));
                    doc.Root.Add(t);
                    item.Values["Custom 1"] = doc.ToString();
                }
            }
            for (var i = 0; i < folder.Count; i++)
                ChangeXML(folder.Children[i]);
        }
        private void button70_Click(object sender, EventArgs e)
        {
            var folder = textBox22.Tag.ToNEFolder();
            ChangeXML(folder);
        }

        private void button22_Click(object sender, EventArgs e)
        {
            var ne = new NEHost2();
            toolStripStatusLabel1.Text = @"";
            var item = ne.Libraries.SelectedItems.Items[0];
            var items = ne.Libraries.ActiveFolder.Items;
            var folderstr = item.get_Values("Title");
            if (folderstr.IndexOf("{") != 0) return;

            folderstr = folderstr.Substring(1, folderstr.Length - 2);
            var folder = folderstr.ToNEFolder();
            var j = folder.IndexOf("*TagTmp");
            if (j < 0)
                folder = folder.Add("*TagTmp");
            else
                folder = folder.get_Children(j);
            folder.DeleteItems(folder.Items, false);
            folder.AddInHistory().Activate();
            for (var i = 0; i < items.Count; i++)
            {
                var t = items.get_Items(i);
                if (t.get_Values("Title").IndexOf("{") < 0)
                {
                    foreach (var k in t.GetPaths())
                    {
                        if (k.IndexOf(folderstr) == 0)
                        {
                            folder.LinkItem(t);
                            break;
                        }
                    }
                }
            }
            toolStripStatusLabel1.Text = @"Finished.";
        }
        //==============history
        private void button9_Click(object sender, EventArgs e)
        {
            FolderHistory.Back();
            ne.MainForm.Show();
        }

        private void button46_Click(object sender, EventArgs e)
        {
            var ne=new NEHost2();
            
            if (ne.Libraries.SelectedItems != null)
            {
                var ftmp = ne.Libraries.SelectedItems.Items[0].FolderItemGo();
                //ftmp.Activate();
                if(ftmp!=null)
                ftmp.AddInHistory();
                else
                    ne.Libraries.ActiveFolder.AddInHistory();
            }
            else
            {
                ne.Libraries.ActiveFolder.AddInHistory();
            }
            toolStripStatusLabel1.Text = "工作目录已设置.";
            this.WindowState = FormWindowState.Normal;
        }

        private void button16_Click(object sender, EventArgs e)
        {
            FolderHistory.Front();
            ne.MainForm.Show();
        }

        private void button36_Click_1(object sender, EventArgs e)
        {
            var ne = new NEHost2();
            var items = ne.Libraries.SelectedItems;
            for (var i = 0; i < items.Count; i++)
            {
                var t = items.get_Items(i);
                var tmp = t.get_Values("Title");
                t.set_Values("Title", t.get_Values("Translated Title"));
                t.set_Values("Translated Title", tmp);

                tmp = t.get_Values("Author");
                t.set_Values("Author", t.get_Values("Translated Author"));
                t.set_Values("Translated Author", tmp);

                tmp = t.get_Values("Journal");
                t.set_Values("Journal", t.get_Values("Tertiary Title"));
                t.set_Values("Tertiary Title", tmp);
            }
            toolStripStatusLabel1.Text = "交换已完成.";
        }
        //=======pdf
        private void button72_Click(object sender, EventArgs e)
        {
            var dlg = new FolderBrowserDialog();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                textBox8.Text = dlg.SelectedPath;
                Settings.Default.PdfOutputFolder = textBox8.Text;
                Settings.Default.Save();
            }
        }

        private void button74_Click(object sender, EventArgs e)
        {
            DirectoryInfo TheFolder = new DirectoryInfo(textBox8.Text);
            //遍历文件夹
            foreach (DirectoryInfo NextFolder in TheFolder.GetDirectories())
                Directory.Delete(NextFolder.FullName,true);
            //遍历文件
            foreach (FileInfo NextFile in TheFolder.GetFiles())
                System.IO.File.Delete(NextFile.Name);

            var ne = new NEHost2();
            var AjiFolder = GetAjiFolder();

            var t = AjiFolder.GetSubFolder("Output");
            t.DeleteItems(t.Items, false);

            toolStripStatusLabel1.Text = "清空已完成.";
        }


        private void button49_Click(object sender, EventArgs e)
        {
            var ne = new NEHost2();
            INEFolder UnProFolder;
            var AjiFolder = GetAjiFolder();

            UnProFolder = AjiFolder.GetSubFolder("UnProcessed");
            var updated = AjiFolder.GetSubFolder("Updated");


            foreach (var pdf in Directory.GetFiles(textBox8.Text, "*.pdf", SearchOption.AllDirectories))
            {
                var pos = pdf.LastIndexOf("\\");
                var name = pdf.Substring(pos + 1);
                try
                {
                    pos = name.IndexOf("-");
                    var id = name.Substring(0, pos);
                    var item = AjiFolder.GetSubFolder("Output").FindItemFromID(id);
                    if (item == null)
                    {
                        Log.Writeline(pdf + " can not be processed.", true);
                        continue;
                    }

                    var pdffiles = item.AttachmentFiles;
                    foreach (var t in pdffiles.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        //pos = t.LastIndexOf("\\");
                        //if (t.Substring(pos+1) != name.Substring(pos + 1, name.Length - pos-1)) continue;

                        var fito = new FileInfo(t);
                        if (fito.Extension != ".pdf") continue;

                        var fifrom = new FileInfo(pdf);

                        if (fifrom.LastWriteTime < fito.LastWriteTime)
                        {
                            Log.Writeline(t + " is newer than " + name, true);
                            UnProFolder.LinkItem(item);
                            continue;
                        }
                        else if (fifrom.LastWriteTime == fito.LastWriteTime)
                        {
                            Log.Writeline(item.Values["ID"] + " is no changed.");
                             continue;
                        }

                        System.IO.File.Delete(t);
                        System.IO.File.Copy(pdf, t);

                        Log.Writeline(pdf + " was processed.");
                        updated.LinkItem(item);

                        break;
                    }
                }
                catch
                {
                    Log.Writeline(pdf + " can not be processed.", true);
                    continue;
                }
            }
            toolStripStatusLabel1.Text = "交换已完成.";

        }

        private void button73_Click(object sender, EventArgs e)
        {
            Log.ShowWindow();
        }

 




    }

    public class ComboBoxItem
    {
        public string Text
        {
            get;
            set;
        }
        public string Value
        {
            get;
            set;
        }
        public override string ToString()
        {
            return this.Text;
        }
    }

    public class BoxItem<T>
    {
        public BoxItem(string Text, T t)
        {
            this.Text = Text;
            Tag = t;
        }
        public string Text
        {
            get;
            set;
        }
        public T Tag
        {
            get;
            set;
        }
        public override string ToString()
        {
            return this.Text;
        }
    }
}
